package com.glodon.paas.document.web.resource.internal;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.glodon.paas.exception.StorageException;
import com.glodon.paas.storage.BulkStorage;
import com.glodon.paas.storage.ReadResult;

@Component
@Path("/internal/store")
public class StoreResource {

    private static final Logger logger = LoggerFactory.getLogger(StoreResource.class); ;

    @Autowired
    private BulkStorage         storage;

    @GET
    @Path("/{path:.+?}")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response download(@PathParam("path")
    String path) {
        try {
            ReadResult result = storage.read(path);
            String name = path;
            int last = path.lastIndexOf('/');
            if (last >= 0) name = path.substring(last + 1, path.length());
            return Response.ok(result.getInputStream(), MediaType.APPLICATION_OCTET_STREAM_TYPE).header("Content-Length",
                                                                                                        Long.toString(result.getLength())).header("Content-Disposition",
                                                                                                                                                  "attachment; filename=\""
                                                                                                                                                          + name
                                                                                                                                                          + "\"").build();
        } catch (StorageException e) {
            logger.warn("download store resources failure: {}", e.getMessage(), e);
            return Response.status(404).build();
        }
    }

    @POST
    @Path("/{path:.+?}")
    @Consumes(MediaType.APPLICATION_OCTET_STREAM)
    public void upload(@Context
    HttpServletRequest request, @PathParam("path")
    String path, @QueryParam("fileSize")
    Long fileSize, InputStream is) throws IOException {
        try {
            if (fileSize == null) fileSize = Long.parseLong(request.getHeader("Content-Length"));
            storage.write(path, is, fileSize);
        } finally {
            is.close();
        }
    }

    @DELETE
    @Path("/{path:.+?}")
    public Response delete(@PathParam("path") String path) {
        storage.delete(path);
        return Response.ok().build();
    }
}
